package com.skytech.component.monitor.task;

import com.skytech.component.monitor.enterprise_data_monitoring.CrawlerScript;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class TaskManager {

    private static final Logger log = LoggerFactory.getLogger(TaskManager.class);

    private List<CrawlerScript> scriptList;

    private int threadNum=1;

    private AtomicInteger scriptIndex;


    public void setThreadNum(int threadNum) {
        this.threadNum = threadNum;
    }

    public TaskManager(List<CrawlerScript> scriptList) {
        this.scriptList = scriptList;
        scriptIndex = new AtomicInteger(scriptList.size());
    }

    public void rush(){
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            ThreadShell shell = new ThreadShell((l) ->{
                consumer(l);
            },String.valueOf(i));

            Thread thread = new Thread(shell);
            thread.start();
            threadList.add(thread);
        }
        /*for (Thread task : threadList) {
            try {
                task.join();
            } catch (InterruptedException e) {
                log.error("线程同步失败");
            }
        }*/
    }
    private  int next(){
        return this.scriptIndex.decrementAndGet();
    }

    private void consumer(String name){
        int index = next();
        if(index>=0){
            log.debug("第{}条线程开始",name);
            scriptList.get(index).start();
            consumer(name);
        }
    }




}
